package com.evaluation.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.evaluation.common.Result;
import com.evaluation.entity.Weixin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();

        // 记录请求信息
        log.info("LoginInterceptor - 拦截请求: " + method + " " + requestURI);

        // 放行的路径
        if (isExcludedPath(requestURI)) {
            log.info("LoginInterceptor - 放行请求: " + requestURI);
            return true;
        }

        // 处理不同类型的请求
        if (requestURI.startsWith("/evaluation/api/h5/")) {
            return handleH5Request(request, response);
        } else if (requestURI.startsWith("/evaluation/api/admin/")) {
            // admin登录相关接口直接放行
            if (requestURI.equals("/evaluation/api/admin/login") ||
                    requestURI.equals("/evaluation/api/admin/check") ||
                    requestURI.equals("/evaluation/api/admin/logout") ||
                    requestURI.equals("/evaluation/api/admin/captcha")) {
                return true;
            }
            return handleAdminRequest(request, response);
        }
        return true;
    }

    /**
     * 判断是否为排除路径
     */
    private boolean isExcludedPath(String requestURI) {
        // 静态资源
        if (requestURI.contains(".css") || requestURI.contains(".js") ||
                requestURI.contains(".png") || requestURI.contains(".jpg") ||
                requestURI.contains(".ico") || requestURI.contains(".gif")) {
            return true;
        }

        // H5静态页面
        if (requestURI.startsWith("/evaluation/h5/") ||
                requestURI.startsWith("/evaluation/static/h5/")) {
            return true;
        }

        // PC管理后台静态页面
        if (requestURI.startsWith("/evaluation/admin/") ||
                requestURI.startsWith("/evaluation/static/admin/")) {
            return true;
        }

        // 登录相关接口
        if (requestURI.equals("/evaluation/api/h5/auth/check") ||
                requestURI.startsWith("/evaluation/weixin/login") ||
                requestURI.startsWith("/evaluation/wechat/") ||  // 企业微信相关路径
                requestURI.equals("/evaluation/api/admin/login") ||
                requestURI.equals("/evaluation/api/admin/check") ||
                requestURI.equals("/evaluation/api/admin/logout") ||
                requestURI.equals("/evaluation/api/admin/captcha") ||
                requestURI.equals("/evaluation/wechat-test.html") ||  // 测试页面
                requestURI.equals("/evaluation/wechat-error.html") ||  // 企业微信错误页面
                requestURI.equals("/evaluation/") ||
                requestURI.equals("/evaluation")) {
            return true;
        }

        return false;
    }

    /**
     * 处理H5 API请求
     */
    private boolean handleH5Request(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 只从session中获取用户信息，确保安全性
        HttpSession session = request.getSession(false);
        if (session == null) {
            writeJsonResponse(response, Result.error("用户未登录，请先登录"));
            return false;
        }

        Object userObj = session.getAttribute("currentUser");
        String jsxm = (String) session.getAttribute("currentUserName");

        if (userObj == null || StrUtil.isBlank(jsxm)) {
            writeJsonResponse(response, Result.error("登录已过期，请重新登录"));
            return false;
        }

        // 验证用户对象类型
        if (!(userObj instanceof Weixin)) {
            writeJsonResponse(response, Result.error("用户信息异常，请重新登录"));
            return false;
        }

        Weixin user = (Weixin) userObj;

        // 将用户信息设置到请求属性中，供Controller使用
        request.setAttribute("currentUser", user);
        request.setAttribute("currentUserName", jsxm);

        return true;
    }

    /**
     * 处理PC管理后台API请求
     */
    private boolean handleAdminRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(false);

        // 检查管理员登录状态
        if (session == null || session.getAttribute("adminLogin") == null) {
            writeJsonResponse(response, Result.error("管理员未登录"));
            return false;
        }

        String adminUser = (String) session.getAttribute("adminUser");
        if (StrUtil.isBlank(adminUser)) {
            writeJsonResponse(response, Result.error("管理员信息无效"));
            return false;
        }

        // 验证管理员权限（这里可以根据需要扩展）
        request.setAttribute("currentAdmin", adminUser);

        return true;
    }

    /**
     * 处理Web页面请求
     * 注意：此方法已废弃，所有Web请求都直接放行
     * 登录控制由前端页面自行处理（通过localStorage和API检查）
     * 避免服务端重定向造成循环
     */
    @Deprecated
    private boolean handleWebRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 直接放行所有Web页面请求
        // H5和Admin静态页面已在isExcludedPath中排除
        // 登录验证由前端JavaScript和API接口负责
        return true;
    }

    /**
     * 写入JSON响应
     */
    private void writeJsonResponse(HttpServletResponse response, Result<?> result) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJsonStr(result));
        writer.flush();
        writer.close();
    }
}
